package com.easycoding.framework.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class TimeInterceptor implements HandlerInterceptor{

    private static final Log logger = LogFactory.getLog(TimeInterceptor.class);

    //before the actual handler will be executed
    public boolean preHandle(HttpServletRequest request, 
        HttpServletResponse response, Object handler)
        throws Exception {
        long startTime = System.currentTimeMillis();
        request.setAttribute("requestStartTime", startTime);
        return true;
    }

    //after the handler is executed
    public void postHandle(
        HttpServletRequest request, HttpServletResponse response, 
        Object handler, ModelAndView modelAndView)
        throws Exception {

        long startTime = (Long)request.getAttribute("requestStartTime");

        long endTime = System.currentTimeMillis();

        long executeTime = endTime - startTime;
        
        //log it
        if(logger.isDebugEnabled()){
           logger.debug("[" + request.getRequestURL() + "] controller执行耗时 : " + executeTime + "ms");
        }
    }
    
  //after the handler is completion
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, 
            Object handler, Exception exception)
            throws Exception {
    	 long startTime = (Long)request.getAttribute("requestStartTime");
    	 long endTime = System.currentTimeMillis();

         long executeTime = endTime - startTime;
         if(logger.isDebugEnabled()){
             logger.debug("[" + request.getRequestURL() + "] 响应耗时 : " + executeTime + "ms");
          }
    }
}
